package com.command.center.pucms.pucmsgateway.freamwork.shiro;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.command.center.pucms.common.constant.Constant;
import com.command.center.pucms.common.util.SimpleJwtUtil;
import com.command.platform.core.result.Result;
import com.command.platform.redis.template.RedisRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zlb
 * <p>
 * 代码的执行流程preHandle->isAccessAllowed->isLoginAttempt->executeLogin->createToken->onLoginSuccess
 */
@Slf4j
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private RedisRepository redisRepository;

    /**
     * 判断用户是否想要登入。
     * 检测header里面是否包含Authorization字段即可
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        log.info("isLoginAttempt方法");
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(Constant.HTTP_HEADER_TOKEN_KEY);
        return authorization != null;
    }

    /**
     * 创建shiro token
     * @param request
     * @param response
     * @return
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        log.info("createToken方法");
        String jwtToken = ((HttpServletRequest)request).getHeader(Constant.HTTP_HEADER_TOKEN_KEY);
        if(jwtToken!=null)
            return new JWTToken(jwtToken);

        return null;
    }

    /**
     * shiro验证登录
     */
   /* @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws AuthenticationException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader(Constant.HTTP_HEADER_TOKEN_KEY);
        JWTToken token = new JWTToken(authorization);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        try {
            this.getSubject(request, response).login(token);
        } catch (IncorrectCredentialsException e) {
            responseError(response,CodeEnum.TOKEN_INVALID.getMsg());
            return false;
        }
        return true;
    }*/

    /**
     * @pass 注解的方法可以放行不经过验证
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("isAccessAllowed方法");
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if (Constant.METHOD_URL_SET.contains(requestURI)) {
            return true;
        }
        try {
            return executeLogin(request, response);
        } catch (Exception e) {
            System.out.println("错误"+e);
            log.info(e.getMessage());
//            responseError(response,"shiro fail");
            return false;
        }
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


    /**
     * isAccessAllowed为false时调用，验证失败
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        log.info("onAccessDenied");
        this.sendChallenge(request, response);
        responseError(response, "token verify fail");
        return false;
    }


    /**
     * shiro验证成功调用
     *
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        log.info("onLoginSuccess：");
        String jwttoken = (String) token.getPrincipal();
        if (jwttoken != null) {
            try {
                if (SimpleJwtUtil.verify(jwttoken)) {
                    //判断Redis是否存在所对应的RefreshToken
                    String userName = SimpleJwtUtil.getUserName(jwttoken);
                    Long currentTime = SimpleJwtUtil.getCurrentTime(jwttoken);
                    if (redisRepository.exists(userName)) {
                        Long currentTimeMillisRedis = (Long) redisRepository.get(userName);
                        if (currentTimeMillisRedis.equals(currentTime)) {
                            return true;
                        }
                    }
                }
                return false;
            } catch (Exception e) {
                Throwable throwable = e.getCause();
                System.out.println("token验证：" + e.getClass());
                if (e instanceof TokenExpiredException) {
                    System.out.println("TokenExpiredException");
                    if (refreshToken(request, response)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 刷新AccessToken，进行判断RefreshToken是否过期，未过期就返回新的AccessToken且继续正常访问
     * @param request
     * @param response
     * @return
     */
    private boolean refreshToken(ServletRequest request, ServletResponse response) {
        String token = ((HttpServletRequest)request).getHeader(Constant.HTTP_HEADER_TOKEN_KEY);
        String userName = SimpleJwtUtil.getUserName(token);
        Long currentTime=SimpleJwtUtil.getCurrentTime(token);
        // 判断Redis中RefreshToken是否存在
        if (redisRepository.exists(userName)) {
            // Redis中RefreshToken还存在，获取RefreshToken的时间戳
            Long currentTimeMillisRedis = (Long) redisRepository.get(userName);
            // 获取当前AccessToken中的时间戳，与RefreshToken的时间戳对比，如果当前时间戳一致，进行AccessToken刷新
            if (currentTimeMillisRedis.equals(currentTime)) {
                // 获取当前最新时间戳
                Long currentTimeMillis =System.currentTimeMillis();
                //redis重新赋值，和token一个时间戳
                redisRepository.setExpire(userName, currentTimeMillis, Constant.REFRESH_EXPIRE_TIME);
                // 刷新AccessToken，设置时间戳为当前最新时间戳
                token = SimpleJwtUtil.sign(userName, currentTimeMillis);
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setHeader("Authorization", token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
                return true;
            }
        }
        return false;
    }

    private void responseError(ServletResponse response, String msg) {

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(401);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        try {
            String rj = new ObjectMapper().writeValueAsString(Result.failure(401, msg));
            httpResponse.getWriter().append(rj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setRedisRepository(RedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }
}
